import {Component, OnInit} from '@angular/core';
import {AddWmsTraysManageComponent} from '../add-wms-trays-manage.component';
import {ErrRes} from '../../../../../frame/global/err-res';
import {WmsTraysManage} from '../../wms-trays-manage.type';
import {Services} from '../../../../../frame/module/services';
import {HttpRequestClient} from '../../../../../frame/http-request-client/http-request-client';
import {UrlRou} from '../../../../../frame';
import {Zero3Alert} from '../../../../../frame/global/zero3-alert/zero3-alert.component';
import {Zero3Enum} from '../../../../../frame/enum/zero3-enum';
import * as fa from '@fortawesome/free-solid-svg-icons';
import { map, filter } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';
import { WmsWarehouseManage } from '../../../wms-warehouse-manage/wms-warehouse-manage.type';
import { FormBuilder, FormGroup, FormArray, RequiredValidator, Validators } from '@angular/forms';
import { GooTypeLevel2Condition } from 'src/app/module/goods-management/goo-type-level2/goo-type-level2.type';
import { GooTypeLevel1Condition } from 'src/app/module/goods-management/goo-type-level1/goo-type-level1.type';
import { Layer } from '@fortawesome/fontawesome-svg-core';


class Level {
    public index?: number;
    public id: string;
    public name: string;
}

@Component({
    selector: 'app-main-add-wms-trays-manage',
    templateUrl: './main-add-wms-trays-manage.component.html',
    styleUrls: ['./main-add-wms-trays-manage.component.css']
})
export class MainAddWmsTraysManageComponent implements OnInit {

    enum = Zero3Enum.NUMBER_2_HANZI_TYPE;
    errRes = new ErrRes();
    domain = new WmsTraysManage();
    domains: WmsTraysManage[] = [];
    houses: WmsWarehouseManage[];
    groupForm: FormGroup;
    root: Level[] = [];
    level1Map = new Map<number, Level[]>();
    level2Map = new Map<number, Level[]>();
    LOCATION_NUM = 100;
    locationArr = [];

    extend = {
        domain: {
            house: {
                nickname: '仓库',
                items: [],
                id: '',
                change: (event) => {
                    if (!isNullOrUndefined(event)) {
                        this.extend.domain.area.items = event.areas;
                    } else {
                        this.extend.domain.area.items = [];
                    }
                }
            },
            area: {
                nickname: '库区',
                items: [],
                name: '',
                change: (event) => {
                    if (!isNullOrUndefined(event)) {
                        this.extend.domain.area.name = event.name;
                    } else {
                        this.extend.domain.area.name = '';
                    }
                }
            },
            layer: {
                nickname: '层数',
                items: [],
                id: '',
                change: (event) => {
                    if (isNullOrUndefined(event)) {
                        this.clearForm();
                    } else {
                        console.log('remove');
                        const number = +event.id;
                        const formSize = this.arrForm.length;
                        const result = number - formSize;
                        if (result > 0) {
                            for (let index = 0; index < result; index++) {
                                this.newForm(index);
                            }
                        } else if (result < 0) {
                            for (let index = formSize - 1 ; index >= number; index--) {
                                console.log(index);
                                this.removeForm(index);
                            }
                        }
                    }
                }
            },

            serLevel1: {
                items: [],
                id: '',
                nickname: '一级分类'
            },
            serLevel2: {
                items: [],
                id: '',
                nickname: '二级分类'
            },
        },
    };

    func = {
        save: {
            req: (event) => {
                if (!this.groupForm.valid) {
                    console.log(this.groupForm.errors);
                }
                console.log(this.groupForm.value);
                const value = this.groupForm.value;
                const house = value.house; // 仓库
                const area = value.area; // 库区
                const layer = value.layer; // 层数
                const start = + value.start; // 起始位数
                const length = + value.length; // 流水号位数
                const separator = value.separator; // 分隔符
                const storageRack = + value.storageRack; // 货架数量
                const arr = value.arr; // 货架的每层内容
                // 遍历货架
                const trays = [];
                for (let index = start; index < storageRack + start; index++) {
                    const storageNo = this.extend.domain.area.name + this.formatInt(index, length); // 货架编号
                    arr.forEach((item, row) => {
                        const level1 = item.Level1; // 商品一级分类
                        const Level2 = item.Level2; // 商品二级分类
                        const LocationNum = + item.LocationNum; // 货位数
                        const LocationCodeNum = item.LocationCodeNum; // 货位码数
                        // 构建数据
                        // 货架-层-货位数
                        for (let loc = 1; loc <= LocationNum; loc++) {
                            const no = `${storageNo}${separator}${this.formatInt(row + 1, length)}${separator}${this.formatInt(loc, length)}`;
                            const tray = new WmsTraysManage();
                            tray.fkGooTypeLevel1Uuid = level1;
                            tray.fkGooTypeLevel2Uuid = Level2;
                            tray.serLocationCodeNum = LocationCodeNum;
                            tray.serLocationNo = no;
                            tray.fkWmsHouseUuid = house;
                            tray.fkWmsAreaUuid = area;
                            tray.serAudit = Zero3Enum.AUDIT_FLAG_WAIT_SUBMIT;
                            tray.serUsing = Zero3Enum.ENABLE;
                            trays.push(tray);
                        }
                    });
                }
                Services.wmsTraysManage.batchSave(trays, this.func.save.callback).subscribe();
            },
            callback: {
                success: (result) => {
                    HttpRequestClient.router.navigate([UrlRou.wmsTraysManage.list]);
                },
                error: (result) => {
                    this.errRes.error = result.error;
                    this.errRes.statusText = result.statusText;
                }
            }
        },
        loadHouses: () => {
            Services.wmsWarehouseManage.listHouses()
            .pipe(
                filter(item => 'success' === item.code && !isNullOrUndefined(item.domains)),
                map((item: any) => {
                    const domains = item.domains;
                    return domains.map(domain => {
                        const areas = domain.wmsAreas || [];
                        const result = areas.map(area => {
                            return {id: area.uuid, name: area.serName};
                        });
                        return {id: domain.uuid, name: domain.serName, areas: result};
                    });
                })).subscribe(houses => {
                    this.extend.domain.house.items = houses;
                });
        },
        loadLevel1: () => {
            Services.gooTypeLevel1.list(new GooTypeLevel1Condition(), {
                page: 0,
                size: 999,
                orders: 'createTime-desc,serNum-asc'
            }).subscribe(item => {
                if (!isNullOrUndefined(item) && item.code === 'success') {
                    this.extend.domain.serLevel1.items = [];
                    item.page.content.forEach(level1 => {
                        this.root.push({id: level1.uuid, name: level1.serTypeName});
                    });
                }
            });
        },
        loadLevel2: (index: number, serOneId: string) => {
            console.log(serOneId);
            Services.gooTypeLevel2.list(new GooTypeLevel2Condition({oneId: serOneId}), {
                page: 0,
                size: 999,
                orders: 'createTime-desc,serNum-asc'
            }).subscribe(item => {
                if (!isNullOrUndefined(item) && item.code === 'success') {
                    const arr = [];
                    item.page.content.forEach(level1 => {
                        arr.push({id: level1.uuid, name: level1.serTypeName});
                    });
                    this.level2Map.set(index, arr);
                }
            });
        },
        change: (event) => {
            if (!isNullOrUndefined(event)) {
                const index = event.index;
                const level = this.level1Map.get(index);
                this.func.loadLevel2(index, event.id);
            }
        }
    };

    constructor(public addWmsTraysManage: AddWmsTraysManageComponent,
        private fb: FormBuilder) {
        this.addWmsTraysManage.main = this;
    }

    private createForm() {
        return  this.fb.group({
                Level1:  ['', Validators.required],
                Level2:  ['', Validators.required],
                LocationNum:  ['', Validators.required],
                LocationCodeNum:  ['', Validators.required]
              });
    }

    formatInt(num: number, length: number) {
        return (Array(length).join('0') + num).slice(-length);
    }

    newForm(index: number) {
        const arr = this.arrForm;
        arr.push(this.createForm()); // 推送form新表单
        const result: Level[] = [];
        this.root.forEach(item => {
            const level = new Level();
            level.index = index;
            level.id = item.id;
            level.name = item.name;
            result.push(level);
        });

        this.level1Map.set(index, result);
        this.level2Map.set(index, []);
    }

    removeForm(i: number) {
        this.arrForm.removeAt(i);
        this.level1Map.delete(i);
        this.level2Map.delete(i);
    }

    public get arrForm(): FormArray {
        return this.groupForm.get('arr') as FormArray;
    }

    clearForm() {
        const length = this.arrForm.length;
        for (let index = length; index >= 0; index--) {
            this.arrForm.removeAt(index);
        }
    }

    initForm() {
        this.groupForm = this.fb.group({
            house: ['', Validators.required],
            area: ['', Validators.required],
            separator: ['', Validators.required],
            storageRack: ['', Validators.required],
            start: ['', Validators.required],
            length: ['', Validators.required],
            layer: ['', Validators.required],
            arr: this.fb.array([])
        });
    }

    ngOnInit() {
        this.initForm();
        // 加载仓库列表(仓库含有库区)
        this.func.loadHouses();
        this.func.loadLevel1();
        // 初始化层数
        const layersNum = Zero3Enum.LAYER_NUM;
        for (let index = 1; index <= layersNum; index++) {
            this.extend.domain.layer.items.push({id: index.toString(), name: index.toString()});
        }
        // 初始 1-100;
        for (let index = 1; index <= this.LOCATION_NUM; index++) {
            this.locationArr.push({id: index.toString(), name: index.toString()});
        }
    }

    clearLevel2() {
        this.extend.domain.serLevel2.items = [];
    }


}
